/*
 * @Description:
 * @Author: cgt
 * @Date: 2021-12-23 14:05:56
 * @LastEditors: cgt
 * @LastEditTime: 2021-12-28 19:41:21
 */
/**
 * @module init/initMap
 * @desc 初始化地图
 */

import loadjs from 'loadjs';

/**
 * 初始化地图插件
 * @param {Object} config 地图配置参数
 */
export function initPlugin(config) {
  const defaultPlugins = [
    'SGMap.DistrictTask',
    'SGMap.ConvertTask',
    'SGMap.PlaceSearchTask',
    'SGMap.spriteSheet'
  ];
  return new Promise((resolve) => {
    let plugins = defaultPlugins.concat(config.PLUGINS || []);
    SGMap.plugin(plugins)
      .then(() => resolve())
      .catch((err) => {
        console.log('err', err);
        resolve();
      });
  });
}
/**
 * 初始化地图
 * @param {Object} options 地图配置参数
 */
export async function initMap(options) {
  var resources = options.sdk_resources;
  var mapOption = Object.assign(
    {},
    {
      localIdeographFontFamily: 'Microsoft YoHei',
      preserveDrawingBuffer: true
    },
    options.base
  );

  if (!options.base.copy) {
    if (resources) {
      console.log('地图资源加载地址', resources);
      await loadjs(resources, { returnPromise: true }).catch((err) => {
        alert(
          '资源加载失败，请在稍后打开的窗口内按照以下步骤执行后刷新页面。\n1.点击“高级”\n2.点击“继续前往……”'
        );
        window.open(err[0], 'blank');
      });
    }
    await SGMap.tokenTask.login(mapOption.key, mapOption.sn);
    await initPlugin(options.config);
  }

  var map = new SGMap.Map(mapOption);
  return new Promise((resolve) => {
    map.on('load', () => {
      resolve(map);
    });
  });
}

